package server;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

/**
 * @author KEM
 * 
 */

class ScreenSender extends Thread {

	Socket client = null;
	Robot robot = null;
	Rectangle rectangle = null;
	boolean loop = true;
	ObjectOutputStream oos = null;

	public ScreenSender(Socket client, Robot robot, Rectangle rect) {
		this.client = client;
		this.robot = robot;
		rectangle = rect;
		start();
	}

    @Override
	public void run() {
		boolean first = true;		
		while (loop) {
			if (first) {
				first = false;
				try {
					oos = new ObjectOutputStream(client.getOutputStream());
					oos.writeObject(rectangle);
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
			BufferedImage image = robot.createScreenCapture(rectangle);				
			try {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ImageIO.write(image, "jpg", baos);									
				oos.writeObject(baos.toByteArray());
				oos.reset();
			} catch (IOException ex) {
				ex.printStackTrace();
				loop = false;
			}
                try {
                    sleep(10);
                } catch (InterruptedException ex) {
                    Logger.getLogger(ScreenSender.class.getName()).log(Level.SEVERE, null, ex);
                }
			
		}

	}

}
